package com.newlink.building.common_base.utils

import android.util.Log
import org.json.JSONException
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*

/**
 * 增强版日志工具类 - 让 logcat 输出更直观
 * @Author: Enhanced by Claude
 * @Date: 2025-09-15
 * @Description: 提供格式化、美化的日志输出，便于调试和问题排查
 */
object EnhancedLogger {

    private const val TAG_PREFIX = "NewLink"
    private const val MAX_LOG_LENGTH = 4000
    private val dateFormat = SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault())

    // 日志级别枚举
    enum class LogLevel(val symbol: String, val color: String) {
        VERBOSE("💬", ""),
        DEBUG("🐛", ""),
        INFO("ℹ️", ""),
        WARN("⚠️", ""),
        ERROR("❌", ""),
        SUCCESS("✅", ""),
        NETWORK("🌐", ""),
        SERVICE("⚙️", ""),
        UI("🖼️", ""),
        DATABASE("💾", "")
    }

    /**
     * 通用日志方法
     */
    public fun log(level: LogLevel, tag: String, message: String, throwable: Throwable? = null) {
        val timestamp = dateFormat.format(Date())
        val formattedTag = "$TAG_PREFIX-$tag"
        val formattedMessage = "${level.symbol} [$timestamp] $message"

        // 如果消息太长，分割输出
        if (formattedMessage.length > MAX_LOG_LENGTH) {
            val chunks = formattedMessage.chunked(MAX_LOG_LENGTH)
            chunks.forEachIndexed { index, chunk ->
                val chunkMessage = if (index == 0) chunk else "    ↳ $chunk"
                logToSystem(level, formattedTag, chunkMessage, if (index == 0) throwable else null)
            }
        } else {
            logToSystem(level, formattedTag, formattedMessage, throwable)
        }
    }

    internal fun logToSystem(level: LogLevel, tag: String, message: String, throwable: Throwable? = null) {
        when (level) {
            LogLevel.VERBOSE -> Log.v(tag, message, throwable)
            LogLevel.DEBUG -> Log.d(tag, message, throwable)
            LogLevel.INFO -> Log.i(tag, message, throwable)
            LogLevel.WARN -> Log.w(tag, message, throwable)
            LogLevel.ERROR -> Log.e(tag, message, throwable)
            else -> Log.i(tag, message, throwable)
        }
    }

    // ========== 基础日志方法 ==========

    fun v(tag: String, message: String) = log(LogLevel.VERBOSE, tag, message)
    fun d(tag: String, message: String) = log(LogLevel.DEBUG, tag, message)
    fun i(tag: String, message: String) = log(LogLevel.INFO, tag, message)
    fun w(tag: String, message: String, throwable: Throwable? = null) = log(LogLevel.WARN, tag, message, throwable)
    fun e(tag: String, message: String, throwable: Throwable? = null) = log(LogLevel.ERROR, tag, message, throwable)
    fun success(tag: String, message: String) = log(LogLevel.SUCCESS, tag, message)

    // ========== 专业化日志方法 ==========

    /**
     * 网络请求日志
     */
    fun network(tag: String, url: String, method: String = "GET", params: String? = null, response: String? = null) {
        val message = buildString {
            appendLine("🌐 NETWORK REQUEST")
            appendLine("┌─────────────────────────────────────")
            appendLine("│ METHOD: $method")
            appendLine("│ URL: $url")
            if (!params.isNullOrEmpty()) {
                appendLine("│ PARAMS: $params")
            }
            if (!response.isNullOrEmpty()) {
                appendLine("│ RESPONSE: $response")
            }
            append("└─────────────────────────────────────")
        }
        log(LogLevel.NETWORK, tag, message)
    }

    /**
     * 网络错误日志
     */
    fun networkError(tag: String, url: String, error: String, code: Int? = null) {
        val message = buildString {
            appendLine("❌ NETWORK ERROR")
            appendLine("┌─────────────────────────────────────")
            appendLine("│ URL: $url")
            if (code != null) {
                appendLine("│ CODE: $code")
            }
            appendLine("│ ERROR: $error")
            append("└─────────────────────────────────────")
        }
        log(LogLevel.ERROR, tag, message)
    }

    /**
     * JSON 格式化日志
     */
    fun json(tag: String, title: String, jsonString: String?) {
        if (jsonString.isNullOrEmpty()) {
            log(LogLevel.INFO, tag, "$title: [Empty JSON]")
            return
        }

        try {
            val jsonObject = JSONObject(jsonString)
            val prettyJson = jsonObject.toString(2)
            val message = buildString {
                appendLine("📋 $title")
                appendLine("┌─────────────────────────────────────")
                prettyJson.lines().forEach { line ->
                    appendLine("│ $line")
                }
                append("└─────────────────────────────────────")
            }
            log(LogLevel.INFO, tag, message)
        } catch (e: JSONException) {
            log(LogLevel.WARN, tag, "$title: [Invalid JSON] $jsonString")
        }
    }

    /**
     * 服务状态日志
     */
    fun service(tag: String, serviceName: String, action: String, status: String) {
        val message = buildString {
            appendLine("⚙️ SERVICE STATUS")
            appendLine("┌─────────────────────────────────────")
            appendLine("│ SERVICE: $serviceName")
            appendLine("│ ACTION: $action")
            appendLine("│ STATUS: $status")
            append("└─────────────────────────────────────")
        }
        log(LogLevel.SERVICE, tag, message)
    }

    /**
     * MQTT 消息日志
     */
    fun mqtt(tag: String, topic: String, message: String, direction: String = "RECEIVE") {
        val symbol = if (direction == "SEND") "📤" else "📥"
        val formattedMessage = buildString {
            appendLine("$symbol MQTT MESSAGE")
            appendLine("┌─────────────────────────────────────")
            appendLine("│ DIRECTION: $direction")
            appendLine("│ TOPIC: $topic")
            appendLine("│ MESSAGE: $message")
            append("└─────────────────────────────────────")
        }
        log(LogLevel.NETWORK, tag, formattedMessage)
    }

    /**
     * 用户操作日志
     */
    fun userAction(tag: String, action: String, details: String? = null) {
        val message = buildString {
            appendLine("👤 USER ACTION")
            appendLine("┌─────────────────────────────────────")
            appendLine("│ ACTION: $action")
            if (!details.isNullOrEmpty()) {
                appendLine("│ DETAILS: $details")
            }
            append("└─────────────────────────────────────")
        }
        log(LogLevel.INFO, tag, message)
    }

    /**
     * 生命周期日志
     */
    fun lifecycle(tag: String, component: String, event: String, extra: String? = null) {
        val message = buildString {
            appendLine("🔄 LIFECYCLE")
            appendLine("┌─────────────────────────────────────")
            appendLine("│ COMPONENT: $component")
            appendLine("│ EVENT: $event")
            if (!extra.isNullOrEmpty()) {
                appendLine("│ EXTRA: $extra")
            }
            append("└─────────────────────────────────────")
        }
        log(LogLevel.INFO, tag, message)
    }

    /**
     * 性能日志
     */
    fun performance(tag: String, operation: String, duration: Long, unit: String = "ms") {
        val status = when {
            duration < 100 -> "✅ FAST"
            duration < 500 -> "⚠️ SLOW"
            else -> "❌ VERY SLOW"
        }

        val message = buildString {
            appendLine("⏱️ PERFORMANCE")
            appendLine("┌─────────────────────────────────────")
            appendLine("│ OPERATION: $operation")
            appendLine("│ DURATION: $duration $unit")
            appendLine("│ STATUS: $status")
            append("└─────────────────────────────────────")
        }
        log(LogLevel.INFO, tag, message)
    }

    /**
     * 数据库操作日志
     */
    fun database(tag: String, table: String, operation: String, result: String? = null) {
        val message = buildString {
            appendLine("💾 DATABASE")
            appendLine("┌─────────────────────────────────────")
            appendLine("│ TABLE: $table")
            appendLine("│ OPERATION: $operation")
            if (!result.isNullOrEmpty()) {
                appendLine("│ RESULT: $result")
            }
            append("└─────────────────────────────────────")
        }
        log(LogLevel.DATABASE, tag, message)
    }

    /**
     * 方法进入/退出日志
     */
    fun methodTrace(tag: String, className: String, methodName: String, isEnter: Boolean, params: String? = null) {
        val direction = if (isEnter) "→ ENTER" else "← EXIT"
        val symbol = if (isEnter) "📍" else "📍"

        val message = buildString {
            appendLine("$symbol METHOD TRACE")
            appendLine("┌─────────────────────────────────────")
            appendLine("│ DIRECTION: $direction")
            appendLine("│ CLASS: $className")
            appendLine("│ METHOD: $methodName")
            if (!params.isNullOrEmpty() && isEnter) {
                appendLine("│ PARAMS: $params")
            }
            append("└─────────────────────────────────────")
        }
        log(LogLevel.DEBUG, tag, message)
    }

    /**
     * 分隔线日志
     */
    fun separator(tag: String, title: String = "") {
        val message = if (title.isEmpty()) {
            "═══════════════════════════════════════════════════"
        } else {
            "═══════════════ $title ═══════════════"
        }
        log(LogLevel.INFO, tag, message)
    }

    /**
     * 带调用位置的日志
     */
    inline fun <reified T> logWithLocation(
        level: LogLevel = LogLevel.DEBUG,
        message: String,
        throwable: Throwable? = null
    ) {
        val className = T::class.java.simpleName
        val stackTrace = Thread.currentThread().stackTrace
        val caller = stackTrace.getOrNull(3)
        val methodName = caller?.methodName ?: "unknown"
        val lineNumber = caller?.lineNumber ?: 0

        val formattedMessage = "📍 [$className.$methodName:$lineNumber] $message"
        log(level, className, formattedMessage, throwable)
    }
}